import router from "./router";
import NProgress from "nprogress";
import { useUserStore } from "@/store/modules/user";
import { validaEmpty } from "@/utils/validate";
import type { RouteRecordRaw } from "vue-router";
import { usePermissionStoreWithOut } from "@/store/modules/permission";
const permissionStore = usePermissionStoreWithOut();
NProgress.configure({
  showSpinner: false,
});
const whiteList = ["/login"]; // 不重定向白名单
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  NProgress.start();
  const isLogin = validaEmpty(to.meta && to.meta.isLogin)
    ? to.meta.isLogin
    : true;
  if (userStore.getToken) {
    if (userStore.getUser && permissionStore.getIsAddRouters) {
      NProgress.done();
      next();
    } else {
      await userStore.getuserInfo().catch(() => {}); // 每次刷新都获取最新的用户信息 已防止权限更新了，还需要退出后重新登录
      await permissionStore.getRouter(); // 获取异步的路由表 => 后续若权限路由可在此添加

      permissionStore.getAddRouters.forEach((route) => {
        router.addRoute(route as RouteRecordRaw); // 动态添加可访问路由表
      });

      NProgress.done();
      const redirectPath = from.query.redirect || to.path;
      const redirect = decodeURIComponent(redirectPath as string);
      const nextData =
        to.path === redirect ? { ...to, replace: true } : { path: redirect };
      permissionStore.setIsAddRouters(true);

      next(nextData);
    }
  } else {
    NProgress.done();
    if (isLogin) {
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
      }
    } else {
      next();
    }
  }
});
router.afterEach(() => {
  NProgress.done();
});
